﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using  Microsoft.Extensions.Configuration;
using System.IO;
using System;
using MDT.LifeSewagePlatform.Conmmon;
using MDT.LifeSewagePlatform.InterfaceService;
using MDT.LifeSewagePlatform.Entity;
using MDT.LifeSewagePlatform.IRepository;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using System.Linq;
using Microsoft.Extensions.Logging;

namespace MDT.LifeSewagePlatform.ServiceInstance.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/file")]
    [ApiController]
    [Authorize]
    public class FileController : BaseController
    {
        #region ctor and prop
        [Autowired]
        private IFileService fileService { get; set; }
        [Autowired]
        private IFileRepository fileRepository { get; set; }
        [Autowired]
        private IConfiguration configuration{ get; set; }
        [Autowired]
        private IDrugService drugService { get; set; }

        [Autowired]
        private ICompanyService companyService { get; set; }

        [Autowired]
        private IDetailService detailService { get; set; }

        [Autowired]

        private ILogger<FileController> logger { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public FileController()
        {
        }
        #endregion

        #region method servcie
        /// <summary>
        /// 上传Excel
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [CustomActionFilter(Role = RoleType.Admin)]
        //100MB
        [RequestSizeLimit(1048576200)]
        public async Task<BaseMessage> AddFile([FromForm] AddFile model)
        {
            return await fileService.Add(model, GetUserID());
        }

        /// <summary>
        /// 更新文件数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        /// 
        [HttpPut("{id}")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<BaseMessage> UpdateFile(int id, [FromForm] UpdateFile model)
        {
            return await fileService.Update(model, id, GetUserID());
            //1,048,576
        }

        /// <summary>
        /// 获取上传的数据
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>

        [HttpGet()]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<BaseMessage> GetFiles([FromQuery] FileParameter Params)
        {
            return await fileService.GetFiles(Params);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        
        [HttpDelete("{id}")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<BaseMessage> DeleteFile(int id)
        {
           return await fileService.SoftDelete(id,GetUserID());
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <returns></returns>
        
        [HttpGet("download")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<IActionResult> DownloadFile()
        {
            return await Task.Run(() =>
            {
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configuration["ExcelTemp"]);

                if (System.IO.File.Exists(filePath))
                {
                    string FileName = System.IO.Path.GetFileName(filePath);
                    var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);

                    return File(fileStream, "application/octet-stream", FileName);
                }
                else
                {
                    return Bad400("表格数据模板不存在请联系管理员!");
                }
            });
        }

        //第几期的
        //城市
        /// <summary>
        /// 获取报告
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        [HttpPost("download/report")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<IActionResult> GetReport([FromBody] ReportParameter Params)
        {
            if (Params.Compares.Count>10)
            {
                return Bad400("当前最多仅仅支持与十个季度做比较!");
            }

            if ((Params.Compares.Count==0))
            {
                Params.Compares.Add(new CompareParameter() { Month=0,Year=0,Quarter=0});
            }
            var dataMessage = await drugService.GetReport(Params);
            string path = dataMessage.GetData<string>();
            if (System.IO.File.Exists(path))
            {
                string FileName = System.IO.Path.GetFileName(path);
                var fileStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);

                return File(fileStream, "application/octet-stream", FileName);
            }
            else
            {
                return Bad400("无数据!");
            }
        }

        /// <summary>
        /// 获取年
        /// </summary>
        /// <param name="companyid"></param>
        /// <returns></returns>
        [HttpGet("years/{companyid}")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<BaseMessage> GetYears(int companyid)
        {
            return await drugService.GetYears(companyid);
        }
        /// <summary>
        /// 获取季度或者月份
        /// </summary>
        /// <param name="companyid"></param>
        /// <param name="year"></param>
        /// <param name="monthorquarter"></param>
        /// <returns></returns>
        [HttpGet("quarter/{companyid}/{year}/{monthorquarter}")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<BaseMessage> GetQuarterOrMonth(int companyid, int year, int monthorquarter = -1)
        {
            return await drugService.GetReportTerm(year, companyid, monthorquarter);
        }
        /// <summary>
        /// 下载excel
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Params"></param>
        /// <returns></returns>
        [HttpGet("download/excel/{Id}")]
        public IActionResult GetExcelFile(int Id, [FromQuery] DownloadParamter Params)
        {
            string dic = Path.Combine(configuration["SewageExcelDataPath"], Params.CompanyID.ToString(), Params.CityID.ToString());
            FileStream fs = null;
            string fileName = string.Empty;
            foreach (var item in Directory.GetFiles(dic))
            {
                if (item.Contains(Id.ToString()))
                {
                    fs =GetFile(item);
                    fileName = Params.FileName+Path.GetExtension(item.GetFileName());
                    break;
                }
            }
            if (fs != null)
            {
                return File(fs,"application/octet-stream",fileName);
            }
            else
            {
                return Bad400("无表格请重新上传!");
            }

        }
        /// <summary>
        /// 上传图片接口
        /// </summary>
        /// <param name="Params"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost("upload/image")]
        public async Task<IActionResult> UploadImage([FromForm]DateParameter Params,List<IFormFile> files)
        {
            #region verify params

            if (files==null || files.Count==0)
            {
                return Bad400("请选择上传的图片!");
            }
            var verifyResualt = Params.Verify();
            if (verifyResualt.Item2 == false)
            {
                return Bad400(verifyResualt.Item1);
            }

            #endregion

            string dic = Path.Combine(configuration["SewageFactoryImagePath"],Params.CompanyID.ToString(),Params.CityID.ToString(),Params.AreaID.ToString());

            await SaveFile(files,dic,extension=>extension.Contains("jpg") 
            || extension.Contains("png") || extension.Contains("gif"));
            return Ok200("图片上传成功");
        }
        /// <summary>
        /// 获取路径
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        [HttpGet("image/paths")]
        public  IActionResult GetPaths([FromQuery]DateParameter Params)
        {
            if (IsAdmin()==false)
            {
                Params.CompanyID = GetCompanyID();
            }

            List<VirtualFileTreeView> fileTree = new List<VirtualFileTreeView>();

            string dic = Path.Combine(configuration["SewageFactoryImagePath"],Params.CompanyID.ToString(),Params.CityID.ToString(),Params.AreaID.ToString());
            if (Directory.Exists(dic))
            {
                if (Directory.GetFiles(dic).Any()==false)
                {
                    return Bad400("暂时没有文件!");
                }
                foreach (var file in Directory.GetFiles(dic))
                {
                    fileTree.Add(new VirtualFileTreeView() {
                        Name=file.GetFileName(), 
                        Value=$"{Params.CompanyID}/{Params.CityID}/{Params.AreaID}/{file.GetFileName()}",
                        Key=$"{Params.CompanyID}/{Params.CityID}/{Params.AreaID}/{file.GetFileName()}" 
                    });
                }
            }
            else
            {
                return Bad400("文件不存在!");
            }
            return Ok200(fileTree, "获取成功!");
        }
        /// <summary>
        /// 获取公司
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ///弃用
        //[HttpGet("company")]
        //[CustomActionFilter(Role = RoleType.Admin)]
        //public async Task<BaseMessage> GetCompanys([FromQuery]CompanyParameter Params)
        //{
        //    var dataMessage= await companyService.GetCompanys(Params);
        //     dataMessage.data.Select(c=>new VirtualFileTreeView() {Name=c.CompanyName,Key=c.ID.ToString(),Value=c.ID.ToString()}).ToList();
        //    return dataMessage;  
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("city/{Id}")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<BaseMessage> GetCityByCompnay(int Id)
        {
            var dataMessage= await companyService.GetCitysByCompany(Id);
            var data=dataMessage.GetData<PieView>();
            dataMessage.data = new VirtualFileTreeView() { Name = data.Name, Key = data.Value.ToString(), Value = data.Value.ToString() };
             return dataMessage;
        }
        /// <summary>
        /// 通过区域获取城市
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("area/{Id}")]
        [CustomActionFilter(Role = RoleType.Admin)]
        public async Task<IActionResult> GetAreaByCity(int Id)
        {
            var data = (await detailService.GetDetails((int)eDictionaryType.Area,Id)).Select(c => new VirtualFileTreeView() { Name = c.RowName, Key = c.ID.ToString(), Value = c.ID.ToString() }).ToList();
            return Ok200(data, "查询成功");
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("image")]
        public  IActionResult DeleteImage(string Id)
        {
            if (string.IsNullOrEmpty(Id))
            {
                return Bad400("请填写key!");
            }
            string dic=configuration["SewageFactoryImagePath"];

            string FileName = Path.Combine(dic, Id.Replace("/", "\\"));
            if (System.IO.File.Exists(FileName))
            {
             System.IO.File.Delete(FileName);
            }
            else
            {
                return Bad400("文件不存在!");
            }
            return Ok200("删除成功!");
        }
        /// <summary>
        /// 系统文件上传接口
        /// </summary>
        /// <param name="files"></param>
        /// <param name="projectName"></param>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        [HttpPost("system")]
        public async Task<BaseMessage> SystemVersion(List<IFormFile> files,[FromForm]string projectName,[FromForm]string moduleName)
        {
            if (files==null ||files.Count==0)
            {
                return new BaseMessage("文件不为空!",400,false);
            }
            foreach (var item in files)
            {
                logger.LogInformation(item.FileName);
                logger.LogInformation(Path.GetDirectoryName(item.FileName));
            }
             string dic =Path.Combine(configuration["ApiVersion"],projectName,moduleName,$"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}");
             await SaveFile(files,dic,exten=>true,false);
             return new BaseMessage("上传成功!", 200, true);
        }
        #endregion
    }
}
